package com.test;

import java.time.Clock;
import java.util.concurrent.*;

public class AQSMain {

    /**
     信号量为5的公平锁
     */
    private static Semaphore semaphore = new Semaphore(5, true);

    public static void main(String[] args) {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                3,
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(2),
                Executors.defaultThreadFactory(),
                (r, executor) -> System.out.println("拒绝策略"));
        //new ThreadPoolExecutor.AbortPolicy()
        try {
            for (int i = 0; i < 10; i++) {
                threadPool.submit(new TaskOne("name" + i));
                // 保证线程执行顺序
                Thread.sleep(5L);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
        System.out.println("end");
    }

    static class TaskOne implements Callable<String> {

        public TaskOne() {
        }

        public TaskOne(String data) {
            this.data = data;
        }

        private String data;

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() throws Exception {
            try {
                System.out.println(this.data);
                semaphore.acquire();
                Thread.sleep(500L);
                System.out.println(Thread.currentThread().getId() + " " + this.data + " " + Clock.systemUTC().millis());
                return this.data;
            } catch (Throwable e) {
                e.printStackTrace();
                return null;
            } finally {
                semaphore.release();
            }
        }
    }
}
